// V-backend/src/models/Product.js
module.exports = (sequelize, DataTypes) => {
  const Product = sequelize.define('Product', {
    product_id: {
      type: DataTypes.INTEGER,
      primaryKey: true,
      autoIncrement: true,
      field: 'product_id'
    },
    anchor_id: {
      type: DataTypes.INTEGER,
      allowNull: false,
      field: 'anchor_id'
    },
    product_name: {
      type: DataTypes.STRING(255),
      allowNull: false,
      field: 'product_name'
    },
    product_description: {
      type: DataTypes.TEXT,
      allowNull: true,
      field: 'product_description'
    },
    price: {
      type: DataTypes.DECIMAL(10, 2),
      allowNull: false,
      field: 'price'
    },
    original_price: {
      type: DataTypes.DECIMAL(10, 2),
      allowNull: true,
      field: 'original_price'
    },
    stock_quantity: {
      type: DataTypes.INTEGER,
      allowNull: false,
      defaultValue: 0,
      field: 'stock_quantity'
    },
    category: {
      type: DataTypes.STRING(100),
      allowNull: true,
      field: 'category'
    },
    status: {
      type: DataTypes.ENUM('active', 'inactive', 'sold_out'),
      defaultValue: 'active',
      field: 'status'
    },
    cover_image: {
      type: DataTypes.STRING(500),
      allowNull: true,
      field: 'cover_image'
    },
    sales_count: {
      type: DataTypes.INTEGER,
      defaultValue: 0,
      field: 'sales_count'
    },
    created_at: {
      type: DataTypes.DATE,
      defaultValue: DataTypes.NOW,
      field: 'created_at'
    },
    updated_at: {
      type: DataTypes.DATE,
      defaultValue: DataTypes.NOW,
      field: 'updated_at'
    }
  }, {
    tableName: 'v_product',
    timestamps: false,
    hooks: {
      beforeUpdate: (product) => {
        product.updated_at = new Date();
      }
    }
  });

  Product.associate = function(models) {
    Product.belongsTo(models.Anchor, {
      foreignKey: 'anchor_id',
      as: 'anchor'
    });
    
    Product.hasMany(models.ProductImage, {
      foreignKey: 'product_id',
      as: 'images'
    });
  };

  return Product;
};